package com.example.sharesinfo.ui;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sharesinfo.R;
import com.example.sharesinfo.base.BaseUIActivity;
import com.example.sharesinfo.db.WordHistory;
import com.example.sharesinfo.entity.Constants;
import com.example.sharesinfo.helper.LitePalHelper;
import com.example.sharesinfo.utils.LogUtils;
import com.example.sharesinfo.utils.OkHttpUtils;
import com.example.sharesinfo.utils.SpUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class WordSearchActivity extends BaseUIActivity implements View.OnClickListener {

    private static final String LOGTAG = "WordSearchActivity:";
    private static final int GetExplainSuccess = 1001;
    private static final int GetExplainFailed = 1002;
    private String inputText;
    private ImageButton mIbBack;
    private TextView tv_clear;
    private GridView mGvHistory;
    private EditText et_search_word;
    private TextView tv_search;
    private SimpleAdapter adapter;
    private List<Map<String, Object>> history;

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case GetExplainSuccess:
                    adapter.notifyDataSetChanged();
                    WordExplainActivity.startActivity(WordSearchActivity.this, String.valueOf(msg.obj));
                    break;
                case GetExplainFailed:
                    adapter.notifyDataSetChanged();
                    Toast.makeText(WordSearchActivity.this, "暂无该词解释", Toast.LENGTH_SHORT).show();
                    break;
                case 404:
                    break;
            }
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_word_search);
        initData();
        initView();
    }

    /**
     * 初始化数据
     */
    private void initData() {
        tv_clear = findViewById(R.id.tv_clear);
        tv_clear.setOnClickListener(this);
        List<WordHistory> wordHistory = LitePalHelper.getInstance().queryWordHistory();
        if (wordHistory.size() == 0) {
            tv_clear = findViewById(R.id.tv_clear);
            tv_clear.setVisibility(View.GONE);
        }
        history = new ArrayList<>();
        for (int i = 0; i < wordHistory.size(); i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("text", wordHistory.get(i).getContent());
            history.add(map);
        }
    }

    private void initView() {
        mIbBack = findViewById(R.id.ib_back);
        mIbBack.setOnClickListener(this);
        et_search_word = findViewById(R.id.et_search_word);
        tv_search = findViewById(R.id.tv_search);
        tv_search.setOnClickListener(this);
        mGvHistory = findViewById(R.id.gv_history);
        String[] from = {"text"};
        int[] to = {R.id.tv_word};
        adapter = new SimpleAdapter(this, history, R.layout.layout_word_search_item, from, to);
        mGvHistory.setAdapter(adapter);
        mGvHistory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                getExplain(history.get(position).get("text").toString());
                //Toast.makeText(WordSearchActivity.this, history.get(position).get("text").toString(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * @type Get
     * @explain 获取词典词条解释（参数为Word和UserId）
     */
    private void getExplain(String inputText) {
        String url = "http://119.23.221.142/api/customer/GetExplain?Word=" + inputText + "&UserId="
                + SpUtils.getInstance().getString(Constants.SP_USER_ID, "");
        OkHttpUtils.getInstance().Get(url, new OkHttpUtils.okHttpListener() {
            Message message = mHandler.obtainMessage();

            @Override
            public void OnSuccess(String s, int code) throws JSONException {
                JSONObject object = new JSONObject(s);
                if (object.getString("code").equals("200")) {
                    message.what = GetExplainSuccess;
                    message.obj = s;
                    mHandler.sendMessage(message);
                } else {
                    message.what = GetExplainFailed;
                    mHandler.sendMessage(message);
                }
            }

            @Override
            public void OnFailed(String s) {
                message.what = 404;
                message.obj = s;
                mHandler.sendMessage(message);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ib_back:
                finish();
                break;
            case R.id.tv_clear:
                LitePalHelper.getInstance().delWordHistory();
                tv_clear.setVisibility(View.GONE);
                history.clear();
                adapter.notifyDataSetChanged();
                break;
            case R.id.tv_search:
                inputText = et_search_word.getText().toString().trim();
                if (TextUtils.isEmpty(inputText)) {
                    return;
                }
                getExplain(inputText);
                LitePalHelper.getInstance().saveWord(inputText);
                Map<String, Object> map = new HashMap<>();
                map.put("text", inputText);
                history.add(map);
                if (tv_clear.getVisibility() == View.GONE) {
                    tv_clear.setVisibility(View.VISIBLE);
                }
                //清空
                et_search_word.setText("");
                break;
        }
    }

}
